# -*- coding: utf-8 -*-

import tw_paths
import tw_oauth
from json import JSONDecoder

#Search:
SEARCH_URL = "http://search.twitter.com/search.json?q="

#General:
TWITTER_URL = "http://api.twitter.com/1/"
# Monitor:
HOME_TIMELINE_URL = TWITTER_URL + "statuses/home_timeline.json"
FRIENDS_TIMELINE_URL = TWITTER_URL + "statuses/friends_timeline.json"
USER_TIMELINE_URL = TWITTER_URL + "statuses/user_timeline/{idu}.json"
MENTIONS_URL = TWITTER_URL + "statuses/mentions.json"
DM_RECEIVED_URL = TWITTER_URL + "direct_messages.json"
DM_SENT_URL = TWITTER_URL + "direct_messages/sent.json"
LST_ST_URL = TWITTER_URL + "{user}/lists/{list}/statuses.json"
LSTS_URL = TWITTER_URL + "{user}/lists.json"
# Post:
UPDATE_STATUS_URL = TWITTER_URL + "statuses/update.json"
NEW_DM_URL = TWITTER_URL + "direct_messages/new.json"
# Tweet:
RT_URL = TWITTER_URL + "statuses/retweet/{id}.json"
DL_URL = TWITTER_URL + "statuses/destroy/{id}.json"
DDL_URL = TWITTER_URL + "direct_messages/destroy/{id}.json"

def read_access_token(user):
	rs=open(tw_paths.ACCSS_TKNS_DIR + user,"r")
	token_info = rs.read()
	rs.close();
	return token_info;

def token_exists(user):
	import os
	return os.path.isfile(tw_paths.ACCSS_TKNS_DIR + user)

def set_tag(original, tag, rtag):
	import string
	return string.replace(original, tag, rtag)

class TwitterSearch(object):
	def __init__(self, query):
		self.query = query
	def search(self):
		import urllib2
		try:
			f = urllib2.urlopen("http://search.twitter.com/search.json?q=" + self.query.replace(" ", "+"))
			json_data=JSONDecoder().decode(f.read())
			f.close()
			return "ok", json_data
		except urllib2.HTTPError, e:
			return "httpError", str(e.code)
		except urllib2.URLError, e:  
			return "urlError", str(e.reason)
	
class TwitterMonitor(object):
	def __init__(self, user):
		self.user = user
		self.url = HOME_TIMELINE_URL
		self.mode = '0'
		self.aux = ''
		if token_exists(self.user):
			self.token = read_access_token(user)
		else:
			self.token = None
		self.params = {}
	def set_mode(self,opt):
		url = {
			'0': HOME_TIMELINE_URL,
			'nr': FRIENDS_TIMELINE_URL,
			'us': USER_TIMELINE_URL,
			'me': MENTIONS_URL,
 			'dr': DM_RECEIVED_URL,
 			'ds': DM_SENT_URL,
 			'ls': LST_ST_URL,
 			'll': LSTS_URL
 		}
 		self.mode = opt
 		self.url = url[opt]
 	def set_params(self, params):
 		self.params = params
 	def set_aux(self,aux):
 		self.aux = aux
	def monitor(self):
		if self.token == None:
			return 'noToken', None
		else:
			if self.mode == 'us':
				self.url = set_tag(self.url,"{idu}",self.aux)
			elif self.mode == 'ls' or self.mode == 'll':
				self.url = set_tag(set_tag(self.url, "{user}", self.user), "{list}", self.aux)
			from tw_oauth import OAuthManager
			oauth = OAuthManager(self.user)
			oauth.get_access_token(self.token)
			state, json = oauth.get_data_from_signed_url(self.url,'GET',self.params)
			return state, JSONDecoder().decode(json)

class TwitterPost(object):
	def __init__(self, user):
		self.user = user
		if token_exists(self.user):
			self.token = read_access_token(user)
		else:
			self.token = None
		self.params = {}
		self.url = UPDATE_STATUS_URL
		self.mode = '0'
	def set_mode(self,opt):
		url = {
			'0': UPDATE_STATUS_URL,
			'd': NEW_DM_URL
 		}
 		self.mode = opt
 		self.url = url[opt]
	def post(self, params):
		if self.token == None:
			return 'noToken', None
		else:
			from tw_oauth import OAuthManager
			oauth = OAuthManager(self.user)
			oauth.get_access_token(self.token)
			state, json = oauth.get_data_from_signed_url(self.url,'POST',params)
			return state, JSONDecoder().decode(json)

class TwitterTweet(object):
	def __init__(self, user, twid):
		self.user = user
		self.twid = twid
		if token_exists(self.user):
			self.token = read_access_token(user)
		else:
			self.token = None
		self.mode = '0'
	def set_mode(self,opt):
		url = {
			'rt': RT_URL,
			'dl': DL_URL,
			'dd': DDL_URL
 		}
 		self.mode = opt
 		self.url = url[opt]
	def execute(self):
		if self.token == None:
			return 'noToken', None
		else:
			from tw_oauth import OAuthManager
			oauth = OAuthManager(self.user)
			oauth.get_access_token(self.token)
			state, json = oauth.get_data_from_signed_url(set_tag(self.url, "{id}", self.twid),'POST')
			return state, JSONDecoder().decode(json)
